import React, { useState, useEffect } from 'react';
import s from './map.module.scss';
const MapComponent = () => {
    const [map, setMap] = useState(null);
    const myGeo = new window.BMapGL.Geocoder();
    useEffect(() => {
        console.log('00');

        setMap(new window.BMapGL.Map(s.map));
    }, []);
    useEffect(() => {
        if (!map) return; // 防止首次进入map值为null
        console.log('map: ', map);
        map.centerAndZoom(new window.BMapGL.Point(116.404, 39.915), 5); // 初始化地图,设置中心点坐标和地图级别
        map.enableScrollWheelZoom(true);
        var zoomCtrl = new window.BMapGL.ZoomControl(); // 添加缩放控件
        map.addControl(zoomCtrl); // 缩放控件未展示 待排查
        map.addEventListener('click', function (e) {
            console.log('点击e: ', e);
            // 点哪里让哪里居中
            map.centerAndZoom(new window.BMapGL.Point(e.latlng.lng, e.latlng.lat), 8);
            myGeo.getLocation(e.latlng, function (res) {
                console.log('res: ', res);
                console.log('点击的省市区信息', res.addressComponents);
                alert(`点击了${res.addressComponents.province}-${res.addressComponents.city}-${res.addressComponents.district}`)
            });
        });
        // 给江苏添加一个区域
        const proname = '江苏省';
        const prokind = 1;
        // const dist = null;
        addDis(proname, prokind);
    }, [map]);
    const addDis = (proname, prokind) => {
        // map.removeDistrictLayer(dist);
        const dist = new window.BMapGL.DistrictLayer({
            name: '(' + proname + ')',
            kind: prokind,
            fillColor: '#618bf8',
            strokeColor: '#daeafa',
            viewport: true,
        });
        map.addDistrictLayer(dist);
        console.log('dist: ', dist);
        // --- 行政区划添加鼠标事件 ---
        dist.addEventListener('mouseover', function (e) {
            console.log('e: ', e);
            e.currentTarget.setFillColor('#9169db');
            myGeo.getLocation(e.latLng, function (res) {
                console.log('res: ', res);
                console.log('鼠标移动实时的省市区信息', res.addressComponents);
            });
        });
        dist.addEventListener('mouseout', function (e) {
            e.currentTarget.setFillColor(e.currentTarget.style.fillColor);
        });
        
        
    };

    return <div id={s.map}></div>;
};
export default MapComponent;
